#include "Queue.h"

void QInit(Queue* pq)
{
	assert(pq);
	pq->head = NULL;
	pq->tail = NULL;
	pq->size = 0;
}

void QDestroy(Queue* pq)
{
	assert(pq);
	QNode* cur = pq->head;
	while (cur != NULL)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->size = 0;
}

void QPush(Queue* pq, QType x)
{
	assert(pq);
	QNode* tmp = (QNode*)malloc(sizeof(QNode));
	if (tmp == NULL)
	{
			perror("malloc");
			exit(-1);
	}
	tmp->data = x;
	tmp->next = NULL;

	if (pq->tail == NULL)
	{
		pq->head = pq->tail = tmp;
	}
	else
	{
		pq->tail->next = tmp;
		pq->tail = tmp;
	}
	pq->size++;
}

void QPop(Queue* pq)
{
	assert(pq);
	assert(pq->size > 0);
	QNode* next = pq->head->next;
	QNode* cur = pq->head;
	free(cur);
	cur = NULL;
	pq->head = next;

	if (pq->head == NULL)
		pq->tail = NULL;
	pq->size--;
}

QType QHead(Queue* pq)
{
	assert(pq);
	assert(pq->head);

	return pq->head->data;
}

QType QTail(Queue* pq)
{
	assert(pq);
	assert(pq->tail);

	return pq->tail->data;
}

bool QEmpty(Queue* pq)
{
	assert(pq);
	return pq->size == 0;
}

int QSize(Queue* pq)
{
	assert(pq);
	return pq->size;
}
